package com.kele.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2021/7/8 16:45
 * @Version:
 */
public class KeleRuleConfig extends AbstractLoadBalancerRule {
    // 每个服务，访问5次，换下一个服务；

    private int total = 0;
    private int currentIndex = 0;

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }

        Server server = null;
        int count = 0;
        while (server == null && count++ < 10) {
            List<Server> reachableServers = lb.getReachableServers();
            List<Server> allServers = lb.getAllServers();
            int upCount = reachableServers.size();
            int serverCount = allServers.size();

            if ((upCount == 0) || (serverCount == 0)) {
                return null;
            }

//            int nextServerIndex = incrementAndGetModulo(serverCount);// 生成区间随机数
//            server = allServers.get(nextServerIndex);// 从活着的服务中，随机获取一个

            // ==========================================================================
            if (total < 5){
                server = reachableServers.get(currentIndex);
                total++;
            }else {
                total = 0;
                currentIndex ++;
                if (currentIndex >= reachableServers.size()){
                    currentIndex = 0;
                }
                server = reachableServers.get(currentIndex);// 从活着的服务中，获取指定的服务来操作
            }
            // ==========================================================================

            if (server == null) {
                /* Transient. */
                Thread.yield();
                continue;
            }

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }

            // Next.
            server = null;
        }

        if (count >= 10) {
        }
        return server;
    }


    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
